<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title id="mytitle">博客列表</title>
    <link rel="stylesheet" href="css/conmmon.css">
    <link rel="stylesheet" href="css/private_letter.css">
    <script src="js/jquery.min.js"></script>
    <script src="js/common.js"></script>
    <script src="js/afterLogin.js"></script>
</head>

<body>
    <!-- 导航栏 -->
    <div class="nav">
        <img src="img/default.jpg" alt="">
        <a class="title" href="blog_list.html">博客系统</a>
        <!-- 用来占据中间位置 -->
        <span class="spacer"></span>
        <a href="javascript:myIndex()">我的主页</a>
        <a href="myinfo.html">个人资料</a>
        <a href="blog_add.html">写博客</a>
        <a href="javascript:mydraft()">我的草稿</a>
        <a href="private_letter.html">好友</a>
        <a href="javascript:logout()">注销</a>
    </div>

    <!-- 版心 -->
    <div class="container">
        <!-- 左侧个人信息 -->
        <div class="container-left">
            <div class="mycard">
                <img src="img/default.jpg" class="photo" alt="">
                <span class="username">cyk(自己)</span>
            </div>
            <div id="friends">
                <div class="friend-card" id="10000">
                    <img src="img/default.jpg" class="photo"  alt="">
                    <span class="username">zhangsan</span>
                    <span class="state" id="state-yes">在线</span>
                </div>

                <div class="friend-card" id="10001">
                    <img src="img/default.jpg" class="photo" alt="">
                    <span class="username">lisi</span>
                    <span class="state" id="state-no">离线</span>
                </div>
            </div>
        </div>
        <!-- 右侧内容详情 -->
        <div class="container-right">

            <div class="blank-list">
                您还未选中或发其聊天，快去跟好友聊一聊吧~
            </div>
            <!--聊天框
            
            <div class="userInfo">
                <span>zhangsan</span>
            </div>

            <div class="chatList">
                <div class="other">
                    <img src="img/default.jpg" class="photo" alt="">
                    <div class="msg">很高兴认识你!</div>
                </div>

                <div class="self">
                    <div class="msg">很高兴认识你!</div>
                    <img src="img/default.jpg" class="photo" alt="">
                </div>
            </div>

            <div class="editor">
                <textarea id="messageText" autofocus="autofocus" maxlength="500" placeholder="请在这里输入您想发送的消息~"></textarea>
                <div class="sendMsg">
                    <button id="sendButton" onclick="sendMsg()">发送</button>
                </div>
            </div> 
            -->

        </div>
    </div>

    <script>

        //自己的头像
        var selfPhoto = "";
        //对方的头像和id
        var otherPhoto = "";
        var otherId = -1;

        //获取当前登录用户信息
        function getCurUserInfo() {
            jQuery.ajax({
                type: "POST",
                url: "/user/info",
                data: {},
                async: false,
                success: function(result) {
                    if(result != null && result.code == 200) {
                        //获取成功，展示信息
                        jQuery(".mycard > .photo").attr("src", result.data.photo);
                        jQuery(".mycard > .username").text(result.data.nickname+"(自己)");
                        //修改全局头像(selfPhoto)
                        selfPhoto = result.data.photo;
                    } else {
                        alert("当前登录用户信息获取失败!");
                    }
                }
            });
        }
        getCurUserInfo();

        //创建 WebSocket 实例
        //TODO: 上传云服务器的时候需要进行修改路径
        var host = window.location.host;
        var websocket = new WebSocket("ws://"+host+"/chat");

        websocket.onopen = function() {
            console.log("连接成功");
        }

        websocket.onclose = function() {
            console.log("连接关闭");
        }

        websocket.onerror = function() {
            console.log("连接异常");
        }

        //监听页面关闭事件，页面关闭之前手动操作 websocket 
        window.onbeforeunload = function() {
            websocket.close();
        }

        //处理服务器返回的响应
        websocket.onmessage = function(e) {
            //获取服务器推送过来的消息
            var jsonInfo = e.data;
            //这里获取到的 jsonInfo 是 JSON 格式的数据，我们需要将他转化成 js 对象
            var result = JSON.parse(jsonInfo);
            if(result != null) {
                //这里的响应有四种可能：1.初始化好友列表(init) 2.推送上线消息(online) 3.下线(offline) 4.聊天消息(msg)
                if(result.msg == "init") {
                    //1.初始化好友列表
                    var friendListDiv = "";
                    for(var i = 0; i < result.data.length; i++) {
                        //获取每一个好友信息
                        var friendInfo = result.data[i];
                        friendListDiv += '<div class="friend-card" id="'+friendInfo.id+'" onclick="javascript:startChat(\''+friendInfo.nickname+'\', \''+friendInfo.photo+'\','+friendInfo.id+')">';
                        friendListDiv += '<img src="'+friendInfo.photo+'" class="photo"  alt="">';
                        friendListDiv += '<span class="username">'+friendInfo.nickname+'</span>';
                        //判断是否在线
                        if(friendInfo.online == "在线") {
                            friendListDiv += '<span class="state" id="state-yes">'+friendInfo.online+'</span>';
                        } else {
                            friendListDiv += '<span class="state" id="state-no">'+friendInfo.online+'</span>';
                        }
                        friendListDiv += '</div>';
                    }
                    //拼接
                    jQuery("#friends").html(friendListDiv);
                } else if(result.msg == "online") {
                    //2.推送上线消息
                    var state = jQuery("#"+result.data+" > .state");
                    state.text("在线");
                    state.attr("id", "state-yes");
                } else if(result.msg == "offline"){
                    //3.推送下线消息
                    var state = jQuery("#"+result.data+" > .state");
                    state.text("离线");
                    state.attr("id", "state-no");
                } else if(result.msg == "msg"){
                    //4.聊天消息
                    var chatDiv = "";
                    chatDiv += '<div class="other">';
                    chatDiv += '<img src="'+otherPhoto+'" class="photo" alt="">';
                    chatDiv += '<div class="msg">'+result.data+'</div>';
                    chatDiv += '</div>';
                    //只有和我聊天的人的 id 和我们发送的对象 id 一致时，才将消息进行拼接
                    if(otherId == result.code) {
                        jQuery(".chatList").append(chatDiv);
                    } 
                    //使用 sessionStorage 存储对话信息
                    var chatData = sessionStorage.getItem(result.code);
                    if(chatData != null) {
                        chatDiv = chatData + chatDiv;
                    }
                    sessionStorage.setItem(result.code, chatDiv);

                } else {
                    //5.错误情况
                    alert(result.msg);
                }
            } else {
                alert("消息推送错误!");
            }
        }

        //点击用户卡片，开启聊天框
        function startChat(nickname, photo, id) {
            //修改全局对方头像和 id
            otherPhoto = photo;
            otherId = id;
            var containerRight = "";
            containerRight += '<div class="userInfo">';
            containerRight += '<span>'+nickname+'</span>';
            containerRight += '</div>';
            containerRight += '<div class="chatList">';
            containerRight += '</div>';
            containerRight += '<div class="editor">';
            containerRight += '<textarea id="messageText" autofocus="autofocus" maxlength="500" placeholder="请在这里输入您想发送的消息~"></textarea>';
            containerRight += '<div class="sendMsg">';
            containerRight += '<button id="sendButton" onclick="sendMsg()">发送</button>';
            containerRight += '</div>';
            containerRight += '</div>';
            //拼接
            jQuery(".container-right").html(containerRight);
            //清空聊天框
            
            //使用 sessionStorage 获取对话信息
            var chatData = sessionStorage.getItem(otherId);
            if(chatData != null) {
                //说明之前有聊天
                jQuery(".chatList").html(chatData);
            }
        }

        //发送信息
        function sendMsg() {
            //非空校验           
            var message = jQuery("#messageText");
            if(message.val() == "") {
                alert("发送信息不能为空!");
                return;
            }
            //触发 websocket 请求前，先检验 websocket 连接是否正常(readyState == OPEN 表示连接正常)
            if (websocket.readyState == websocket.OPEN) {
                //客户端展示
                var chatDiv = "";   
                chatDiv += '<div class="self">';
                chatDiv += '<div class="msg">'+message.val()+'</div>';
                chatDiv += '<img src="'+selfPhoto+'" class="photo" alt="">';
                chatDiv += '</div>';
                jQuery(".chatList").append(chatDiv);
                //消息发送给服务器
                var json = {
                    "code": otherId,
                    "msg": message.val()
                };
                websocket.send(JSON.stringify(json));
                //使用 sessionStorage 存储对话信息
                var chatData = sessionStorage.getItem(otherId);
                if(chatData != null) {
                    chatDiv = chatData + chatDiv;
                }
                sessionStorage.setItem(otherId, chatDiv);
                //清除输入框内容
                message.val("");
            } else {
                alert("当前您的连接已经断开，请重新登录!");
                location.assign("/login.html");
            }
        }


    </script>

</body>

</html>